import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:learning/bean/category_entity.dart';
import 'package:learning/components/MyText.dart';
import 'package:learning/service/CategoryService.dart';

/// 具备展开收起功能的气泡背景文字面板
/// 气泡：背景色为Color(0xFFF8F8F8)的灰色Container
///      右上角为不规则小三角
///
/// 布局规则：
///     组件的背景是气泡背景
///     包装了[BrnExpandableText]组件，具备了展开收起的能力
///
/// ```dart
///   BrnBubbleText(
///      text: '在文本的右下角有更多或者收起按钮',
///   )
///
///   BrnBubbleText(
///      text: '具备展开收起功能的文字面板，在文本的右下角有更多或者收起按钮',
///      maxLines: 2,
///   )
///
/// ```
///
/// 相关文本组件如下:
///  * [BrnExpandableText], 气泡背景的展开收起文本组件
///  * [BrnInsertInfo], 气泡背景的文本组件
///
class SelectedCard extends StatefulWidget {
  /// 显示的文本
  final String? lang;

  /// create BrnBubbleText
  const SelectedCard({Key? key, this.lang = "zh"}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _SelectedCardState createState() => _SelectedCardState();
}

class _SelectedCardState extends State<SelectedCard> {
  final ScrollController _control = new ScrollController();
  String? lang;
  BoxDecoration? borderRadius;
  BoxDecoration? borderRadiusSelected;
  TextStyle? textStyle;
  int selectedIndex = 0;

  late Future<List<CategoryEntity>> futureData;

  @override
  void initState() {
    lang = "zh";
    borderRadius = const BoxDecoration(
        color: Colors.black38,
        borderRadius: BorderRadius.all(Radius.circular(6)));
    borderRadiusSelected = const BoxDecoration(
        color: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(6)));
    super.initState();
  }

  @override
  void setState(VoidCallback fn) {
    // TODO: implement setState
    super.setState(fn);
    borderRadius = const BoxDecoration(
        color: Colors.black38,
        borderRadius: BorderRadius.all(Radius.circular(6)));
    borderRadiusSelected = const BoxDecoration(
        color: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(6)));
    print("Almaxxxxx");
  }

  Future<List<CategoryEntity>> fetchTodo() async {
    //listData=[];

    List<CategoryEntity> listData = await CategoryService.getCategoryList();
    if (listData.length > 0) {
      return listData;
    } else {
      throw Exception('Failed to load data');
    }
  }

  @override
  Widget build(BuildContext context) {
    textStyle = new TextStyle(color: Colors.white, fontWeight: FontWeight.bold);

    futureData = fetchTodo();

    return FutureBuilder<List<CategoryEntity>>(
        future: futureData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return GridView(
                padding: EdgeInsets.all(10.0),
                primary: false,
                shrinkWrap: true,
                controller: _control,
                physics: BouncingScrollPhysics(),
                // 回弹效果
                cacheExtent: 200.0,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: 150.0,
                    mainAxisSpacing: 10.0,
                    crossAxisSpacing: 5.0,
                    childAspectRatio: 3.0 / 2.0),
//      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//        crossAxisCount: 3,
//        mainAxisSpacing: 10.0,
//        crossAxisSpacing: 20.0,
//        childAspectRatio: 3.0/2.0
//      ),
                children: getMoreContainer(snapshot.data));
          } else {
            return Container(
              padding: const EdgeInsets.all(10.0),
              child: Center(
                child: Text(
                  "加载中",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          }
        });
  }

/*
  @override
  void didUpdateWidget(SelectedCard oldWidget) {
  super.didUpdateWidget(oldWidget);
  }*/

  List<Widget> getMoreContainer(List<CategoryEntity>? listData) {
    final box = GetStorage();
    if (listData == null) {
      listData = [];
    }
    print("Leng:${listData.length}");
    List<Widget> list = [];
    for (int i = 0; i < listData.length; i++) {
      CategoryEntity? item = listData.elementAt(i);
      list.add(InkWell(
          onTap: () {
            setState(() {
              selectedIndex = i;
              box.write("categoryId", item.id);
              box.write("categoryName", item.name);
              box.write("categoryContent", item.content);
            });
          },
          child: Container(
            decoration: BoxDecoration(
              color: selectedIndex == i ? Colors.blue : Colors.blue.shade100,
              borderRadius: BorderRadius.circular(8),
              shape: BoxShape.rectangle,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withAlpha(11),
                  offset: const Offset(0, 14),
                  blurRadius: 24,
                  spreadRadius: 0,
                ),
              ],
            ),
            child: Center(
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                        IconData(
                            item.icon != null
                                ? int.parse(item.icon.toString())
                                : 0xe628,
                            fontFamily: 'IconFontIcons'),
                        color: selectedIndex == i
                            ? Colors.white
                            : Colors.blue.shade400),
                    MyText('${item?.name}',
                        style: TextStyle(
                            fontSize: 12,
                            color: selectedIndex == i
                                ? Colors.white
                                : Colors.blue.shade400)),
                    MyText('${item?.content}',
                        style: TextStyle(
                            fontSize: 8,
                            color: selectedIndex == i
                                ? Colors.white.withAlpha(150)
                                : Colors.black.withAlpha(150)))
                  ]),
            ),
          )));
    }
    return list;
  }
}
